<template>
  <el-container id="container_imagecontrol" ref="homeMain">
    <el-aside>
      <el-tree
        :data="dcdata.znodes"
        :props="dcdata.defaultProps"
        @node-click="treeNodeClick"
        :check-on-click-node="true"
        :expand-on-click-node="false"
        :auto-expand-parent="false"
        :highlight-current="true"
        node-key="key"
        :default-expanded-keys="expandedKeys"
      >
        <span class="custom-tree-node" slot-scope="{ node,data}">
          <span>
            <span class="dir" v-if="data.levelTree=='dir'">
              <i class="el-icon-folder"></i>
            </span>
            <span class="docType" v-else-if="data.levelTree=='docType'">
              <i class="el-icon-notebook-1"></i>
            </span>
            <span class="doc" v-else>
              <i class="el-icon-document"></i>
            </span>
            {{ node.label }}
            <span
              v-if="data.imagesCount"
              class="lbl_imgnum"
            >{{data.imagesCount}}</span>
          </span>
        </span>
      </el-tree>
    </el-aside>
    <el-container>
      <el-header>
        <input type="file" ref="fileupload" hidden multiple="multiple" @change="fileChange" />
        <el-button class="toolitem" size="small" type="primary" @click="imageAdd">影像添加</el-button>

        <el-dropdown size="small" split-button type="primary" @command="imglayoutClick">
          图片布局
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="one">单页展示</el-dropdown-item>
            <el-dropdown-item command="two">双页展示</el-dropdown-item>
            <el-dropdown-item command="three">三页展示</el-dropdown-item>
            <el-dropdown-item command="four">四页展示</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-header>
      <el-main>
        <div class="attachFiles">
          <el-link
            type="primary"
            :download="file.fileName"
            v-for="(file) in attachFileList"
            :key="file.fileId"
            :href="file.url||'#'"
          >{{file.fileName.split('-').pop()}}</el-link>
        </div>
        <div
          class="image_group_car"
          v-for="(group,index) in imageList"
          :key="group.groupTitle+index"
        >
          <h3>{{group.groupTitle}}</h3>
          <div class="clear"></div>
          <div :class="['imgdivlayout',imgshowway]" v-for="(img) in group.items" :key="img.fileId">
            <el-image :src="img.url||img.base64" lazy @click="handleImgClick(img.fileId)">
              <div slot="placeholder" class="image-slot">
                努力加载中
                <span class="dot">...</span>
              </div>
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
                <span>图片已不存在</span>
              </div>
            </el-image>
          </div>
          <div class="clear"></div>
        </div>
        <el-image-viewer v-if="showViewer" :url-list="viewerImgList" :on-close="closeViewer" />
      </el-main>
      <el-footer>
        <el-button size="small" type="success" @click="submitUpload">上传到服务器</el-button>
      </el-footer>
    </el-container>
    <el-dialog class="dilProgress" title="上传进度" :visible.sync="dilProgressVisible">
      <span>{{uploadmsg}}</span>
      <el-table :data="todoupfiles">
        <el-table-column type="index" width="40"></el-table-column>
        <el-table-column property="fileName" label="文件名" width="160"></el-table-column>
        <el-table-column label="大小" width="76">
          <template slot-scope="scope">{{ scope.row.fileLen | filesizeFormat }}</template>
        </el-table-column>
        <el-table-column label="上传进度">
          <template slot-scope="scope">
            <el-progress :text-inside="true" :stroke-width="14" :percentage="scope.row.progress"></el-progress>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </el-container>
</template>
<script>
import datacontext from "../assets/js/datacontext.js";
import messagetlp from "../assets/js/messagetlp.js";
import serviceapi from "../assets/js/serviceapi.js";
import utils from "../assets/js/utils.js";
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import { Loading } from "element-ui";

export default {
  created() {},
  mounted() {
    //初始化界面
    this.initUi();
    //初始化加载数据
    this.initTreeData();
  },
  beforeUpdate() {},
  components: { ElImageViewer },
  data: function() {
    return {
      dcdata: datacontext, //整体的树数据
      imageList: [], //显示图片数据
      attachFileList: [], //显示附件数据
      imgSrcList: [],
      curruntNodeData: null, //当前选中的节点数据
      expandedKeys: [],
      showViewer: false,
      viewerImgList: [], //轮播大图的url列表
      imgshowway: "imgtwo",
      //上传进度相关
      dilProgressVisible: false,
      todoupfiles: [],
      uploadmsg: "",

      loadingInstance: null,
      loadOption: {
        target: ".el-main",
        text: "图片加载中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.3)"
      }
    };
  },
  methods: {
    initUi() {},
    async initTreeData() {
      this.curruntNodeData = null;
      this.imageList = [];
      this.attachFileList = [];
      try {
        //初始化树数据
        let { data } = await serviceapi.initview(messagetlp.initview());
        datacontext.assemblytree(data);

        //设置默认展开节点
        this.expandedKeys = this.dcdata.znodes.reduce((s, n) => {
          let returnNodes = [];
          datacontext.getDirNodes(n, returnNodes);
          return s.concat(...returnNodes.map(n => n.key));
        }, []);
        //默认触发第一个节点点击
        this.$nextTick().then(() => {
          const firstNode = document.querySelector(".el-tree-node");
          if (firstNode) firstNode.click();
        });
      } catch (err) {
        this.$Message.error("获取影像目录树数据失败");
      }
    },
    treeNodeClick(data) {
      let nodeData = data;
      if (!nodeData) return;
      //清空上一次的
      this.curruntNodeData = nodeData;
      this.expandedKeys = [data.key];
      this.imageList = [];
      this.attachFileList = [];
      datacontext.getNodeContent(nodeData, this.imageList, this.attachFileList);
      this.imgSrcList = this.imageList.reduce((s, g) => {
        return s.concat(
          g.items.map(img => {
            return { imgKey: img.fileId, url: img.url || img.base64 };
          })
        );
      }, []);
    },
    imageAdd() {
      let nodeData = this.curruntNodeData;
      if (!nodeData) {
        this.$message({
          message: "请选中要添加的文档目录",
          type: "warning"
        });
        return;
      }
      if (nodeData.levelTree === "dir") {
        this.$message({
          message: "请选中一个文档类型目录或文档目录",
          type: "warning"
        });
        return;
      }
      this.$refs["fileupload"].click();
    },
    async fileChange(e) {
      let nodeData = this.curruntNodeData; //当前选中节点
      let files = e.target.files; //添加的图片
      let addAttachfiles = []; //新增的附件
      let addImages = []; //新增的图片
      let docNode = null;
      if (nodeData.levelTree === "docType") {
        docNode = {
          label: nodeData.label + (nodeData.children.length || ""),
          levelTree: "doc",
          docId: utils.getUuid(),
          refDocType: nodeData,
          newadd: true
        };
        nodeData.children.push(docNode);
      } else {
        docNode = nodeData;
      }
      docNode.images = docNode.images || [];
      try {
        this.loadingInstance = Loading.service(this.loadOption);
        let resFiles = await Promise.all(
          Array.from(files).map(f => {
            return utils.loaddingFile(f);
          })
        );
        resFiles.forEach(f => {
          f.docNode = docNode;
          f.isImage ? addImages.unshift(f) : addAttachfiles.unshift(f);
        });
        docNode.images.push(...addImages, ...addAttachfiles);
        //模拟再次点击一下本节点实现刷新
        this.treeNodeClick(this.curruntNodeData);
        this.loadingInstance.close();
      } catch (err) {
        if (this.loadingInstance) this.loadingInstance.close();
        this.$message({
          message: err,
          type: "warning"
        });
      }
    },
    async submitUpload() {
      let files = this.dcdata.znodes.reduce((s, n) => {
        let filestmp = [];
        this.dcdata.getUploadFiles(n, filestmp);
        return s.concat(filestmp);
      }, []);
      if (files.length == 0) {
        this.$message({
          message: "没有要上传的资料",
          type: "warning"
        });
        return;
      }
      //成功上传后的回调
      let successCb = res => {
        let resCount = res.data.fileList.length;
        this.$notify({
          title: "成功",
          message: `本次成功提交${resCount}个影像件`,
          type: "success",
          position: "bottom-left",
          duration: 3000
        });
        this.initTreeData();
      };
      //失败时的回调
      let errorCb = err => {
        this.uploadmsg = "上传影像件失败:" + err;
      };
      this.uploadmsg = "";
      this.dilProgressVisible = true;
      this.todoupfiles = files; //待上传文件列表,用于进度展示
      try {
        //并发上传文件
        let results = await serviceapi.paralleliz(
          files.reduce((s, f, index) => {
            if (f.filePath) return s; //若已上传过,无需再次上传,达到断点续传的效果
            let formdata = new window.FormData();
            formdata.append(f.fileId, f.file);
            let onUploadProgress = progressEvent => {
              f.progress =
                ((progressEvent.loaded / progressEvent.total) * 100) | 0;
              this.$set(this.todoupfiles, index, f);
            };
            return s.concat(
              serviceapi.fileupload(formdata, { onUploadProgress })
            );
          }, [])
        );
        //统一赋值图片路径信息
        results.forEach(({ data: res }) => {
          res.data.forEach(r => {
            let file = files.find(f => f.fileId + "" === r.fileDocumentName);
            if (file) file.filePath = r.filePath;
          });
        });
        let docparameterList = [];
        let fileparameterList = [];
        files.forEach(f => {
          if (!f.filePath) return;
          if (
            f.refDoc &&
            f.refDoc.newadd &&
            !docparameterList.find(_ => _.docId === f.refDoc.docId)
          ) {
            //有新的doc需要添加
            docparameterList.push(
              messagetlp.getdocparameter({
                docId: f.refDoc.docId,
                docName: f.refDoc.label,
                parentDirid: f.refDoc.refDocType.dirId,
                docType: f.refDoc.refDocType.docTypeCode,
                docTypeName: f.refDoc.refDocType.docTypeName,
                pageCount: f.refDoc.images.length
              })
            );
          }
          fileparameterList.push(
            messagetlp.getfileparameterList({
              docId: f.refDoc.docId,
              docType: f.refDoc.refDocType.docTypeCode,
              docTypeName: f.refDoc.refDocType.docTypeName,
              fileName: f.fileName,
              filePath: f.filePath
            })
          );
        });
        //上传索引到数据库
        let createImageDocumentJson = messagetlp.createImageDocument();
        Object.assign(createImageDocumentJson.inparameterList[0], {
          docparameterList,
          fileparameterList
        });
        let { data } = await serviceapi.createImageDocument(
          createImageDocumentJson
        );
        if (data.code === "200") {
          successCb(data);
          setTimeout(() => {
            this.dilProgressVisible = false;
          }, 4000);
        } else {
          errorCb(data.message);
        }
      } catch (err) {
        errorCb(err);
      }
    },

    attachFileClick(file) {},
    imglayoutClick(showway) {
      this.imgshowway = `img${showway}`;
    },
    handleImgClick(imgKey) {
      let index = this.imgSrcList.findIndex(img => img.imgKey == imgKey);
      if (index != -1) {
        this.viewerImgList = this.imgSrcList.slice(index).map(img => img.url);
        this.showViewer = true;
      }
    },
    closeViewer() {
      this.showViewer = false;
    }
  },
  filters: {
    filesizeFormat(fileLen) {
      return utils.fileSizeConvert(fileLen);
    }
  }
};
</script>


<style lang="scss" scoped>
#container_imagecontrol {
  position: absolute;
  top: 0px;
  bottom: 0px;
  left: 0px;
  right: 0px;
  .el-aside {
    border-right: 1px gray solid;
    .el-tree {
      .lbl_imgnum {
        color: red;
        font-weight: bold;
      }
    }
  }
  .el-container {
    position: relative;
    width: calc(100%);
    .el-header {
      padding: 4px;
      height: 40px !important;
      position: relative;
      top: 0px;
      left: 0px;
      right: 0px;
      .toolitem {
        margin: 0px 5px 0px 5px;
      }
    }
    .el-main {
      margin: 0px;
      padding: 0px;
      .attachFiles {
        .el-button {
          margin: 6px;
          padding: 0px;
        }
        .el-link {
          margin: 6px;
        }
      }
      .image_group_car {
        h3 {
          margin: 0px;
        }

        img {
          // width: 100%;
          // height: 100%;
          // margin: 0px;
          // padding: 0px;
        }
        .el-image {
          width: 100%;
          height: 100%;
          margin: 0px;
          padding: 0px;
        }
        .imgdivlayout {
          padding: 4px;
          float: left;
        }
        .imgone {
          width: 100%;
        }
        .imgtwo {
          width: 48%;
          height: 400px;
        }
        .imgthree {
          width: 32%;
          height: 300px;
        }
        .imgfour {
          width: 24%;
          height: 240px;
        }

        .clear {
          clear: both;
        }
      }
    }
    .el-footer {
      padding: 4px;
      height: 40px !important;
      position: absolute;
      bottom: 0px;
      left: 0px;
      right: 0px;
    }
  }
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.dir {
  color: #ECC84F;
}
.docType {
  color: rgb(43, 128, 226);
}
.doc {
  color: rgb(128, 128, 128);
}
</style>
<style lang="scss">
html,
body {
  margin: 0px;
  padding: 0px;
}
 .el-tree {
  background: none;
  color: black;
}
.el-tree-node__expand-icon {
 // color: black;
}
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: rgb(194, 191, 191);
} 
.dilProgress {
  .el-dialog__header {
    padding: 6px 20px 3px;
    .el-dialog__headerbtn {
      top: 6px;
    }
  }
  .el-dialog__body {
    padding: 4px 20px;
  }
  .el-table td,
  .el-table th {
    padding: 5px 0;
  }
}
</style>
